package com.sziit.se.highconcurrency.order.application.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sziit.se.highconcurrency.common.annotation.IgnoreCheck;
import com.sziit.se.highconcurrency.common.constant.SystemConstants;
import com.sziit.se.highconcurrency.common.entity.UserInfoVo;
import com.sziit.se.highconcurrency.common.result.DataResult;
import com.sziit.se.highconcurrency.common.result.PageResult;
import com.sziit.se.highconcurrency.common.result.Result;
import com.sziit.se.highconcurrency.common.result.ResultUtil;
import com.sziit.se.highconcurrency.common.tool.LocalUser;
import com.sziit.se.highconcurrency.order.application.entity.*;
import com.sziit.se.highconcurrency.order.application.feignclient.ProductFeign;
import com.sziit.se.highconcurrency.order.application.feignclient.UserFeign;
import com.sziit.se.highconcurrency.order.application.service.IOrderDetailService;
import com.sziit.se.highconcurrency.order.application.service.IOrderService;
import lombok.AllArgsConstructor;
import org.aspectj.weaver.ast.Or;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.UUID;

import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author dongchunkeng
 * @since 2022-11-09
 */
@RestController
@AllArgsConstructor
@RequestMapping("/order")
public class OrderDetailController {

    private final IOrderDetailService orderDetailService;

    private final IOrderService orderService;

    private final ProductFeign productFeign;

    private final UserFeign userFeign;

//    @GetMapping
//    @IgnoreCheck
//    @RequestMapping("")
//    public Result getOrderInfo(@RequestParam(value = "order_id") String orderId) throws InterruptedException {
//        Order order = orderService.getOneData(orderId);
//        List<OrderDetail> orderDetails = orderDetailService.getProductByOrderId(orderId);
//        OnlyOrderInfo orderInfo = new OnlyOrderInfo();
//        orderInfo.setOrderDetailList(orderDetails);
//        orderInfo.setUser_id(order.getUserId());
//        return ResultUtil.data(orderInfo);
//    }


    @IgnoreCheck
    @PostMapping(value = "/create")
    @Transactional
    public Result createOrder(@RequestBody CreateOrderReq createOrderReq) throws Exception {

        String orderId = UUID.randomUUID().toString();
        String token = LocalUser.getToken();
        UserInfoVo userInfoVo = LocalUser.getUser();
        String userId = userInfoVo.getUserId();
        List<ProductOrder> productDetails = createOrderReq.getProductOrderList();
        for (ProductOrder productOrder : productDetails) {
            String productId = productOrder.getProductId();
            DataResult productResult = productFeign.getProductById(token, productId);
            LinkedHashMap productHashMap = (LinkedHashMap) productResult.getData();
            Product product = JSON.parseObject(JSON.toJSONString(productHashMap), Product.class);

            if (null == product) {
                log.println("product is not on sail");
                throw new Exception("该商品不存在");
            }
            if (productOrder.getAmount() > product.getInventory()) {
                log.println("Inventory is lack");
                throw new Exception("库存不足，请减少购买数量");
            }
        }

        //根据订单中的每个商品购买数量，更新库存信息并将订单的详情保存在order_detail表中
        List<OrderDetail> orderDetails = new ArrayList<>();
        for (ProductOrder productOrder : productDetails) {
            String productId = productOrder.getProductId();
            DataResult productResult = productFeign.getProductById(token,productId);
            LinkedHashMap productHashMap = (LinkedHashMap) productResult.getData();
            Product product = JSON.parseObject(JSON.toJSONString(productHashMap), Product.class);
            System.out.println("inventory is " + product.getInventory() );
            int newInventroy = product.getInventory() - productOrder.getAmount();
            System.out.println("inventory is " + productOrder.getAmount() );
            MultipartFile image = new MockMultipartFile("file",new byte[0]);
//            Content-Type设置成multipart/form-data

            productFeign.updateProductInventory(token, productId, newInventroy);
            orderDetailService.insertOrderDetail(orderId, productId, productOrder.getAmount());
            OrderDetail orderDetail = orderDetailService.getProductByOrderIdAndProductId(orderId,productId);
            //组装orderDetails，作为返回值一部分返回

            orderDetails.add(orderDetail);
        }
        //订单信息存入订单表中
        Boolean orderSuccess = orderService.insertOrder(orderId, userId, SystemConstants.ORDER_STATUS_WAIT_PAY);
        OnlyOrderInfo orderInfo = new OnlyOrderInfo();
        orderInfo.setOrderDetailList(orderDetails);
        orderInfo.setUser_id(userId);
        return ResultUtil.data(orderInfo);
    }

    @GetMapping
    @RequestMapping("/query-by-id")
    public Result getOrderDetail(@RequestParam(value = "orderId") String orderId) throws InterruptedException {
        //将购买的产品信息和用户信息组装最后的响应体
        OrderDetailRsp orderDetailRsp = getOneOrderDetailInfo(orderId);

        return ResultUtil.data(orderDetailRsp);
    }

//    @GetMapping
//    @IgnoreCheck
//    @RequestMapping("/query-by-id")
//    public Result getOrderInfoByPage(@RequestParam(value = "orderId") String orderId) throws InterruptedException {
//        Order order = orderService.getOneData(orderId);
//        List<OrderDetail> orderDetails = orderDetailService.getProductByOrderId(orderId);
//        OnlyOrderInfo orderInfo = new OnlyOrderInfo();
//        orderInfo.setOrderDetailList(orderDetails);
//        orderInfo.setUser_id(order.getUserId());
//
//        return ResultUtil.data(orderInfo);
//    }

    @GetMapping
    @IgnoreCheck
    @RequestMapping("/query-by-page")
    public Result getOrderInfoByPage(@RequestParam(value = "pageNumber") int pageNumber,
                                     @RequestParam(value = "pageSize") int pageSize) throws InterruptedException {
        UserInfoVo userInfoVo = LocalUser.getUser();
//        pageNumber = pageNumber - 1;
        IPage<OrderDetailRsp> orderDetailRspIPage = getMultiOrderDetailInfo(pageNumber, pageSize, userInfoVo.getUserId());

        return ResultUtil.data(orderDetailRspIPage);
    }


    /**
     *
     */
    @PutMapping
    @RequestMapping("/pay")
    public Result updateOrderStatus(@RequestParam("orderId") String orderId) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq(orderId != null ,"order_id", orderId);
        Order order = new Order();
        order.setOrderId(orderId);
        order.setStatus(SystemConstants.ORDER_STATUS_FINISH_PAY);
        orderService.update(order, wrapper);
        return ResultUtil.data(orderService.getOneData(orderId));
    }



    private UserVo getUserInfo(String userId) {
        String token = LocalUser.getToken();
        DataResult userResult = userFeign.getUserById(token, userId);
        LinkedHashMap userHashMap = (LinkedHashMap) userResult.getData();
        UserVo userVo = JSON.parseObject(JSON.toJSONString(userHashMap), UserVo.class);
        return userVo;
    }

    private OrderDetailRsp getOneOrderDetailInfo(String orderId) {
        Order order = orderService.getOneData(orderId);
        List<OrderDetail> orderDetails = orderDetailService.getProductByOrderId(orderId);


        //从product微服务查询product信息，并组装成List<ProductDetail>
        List<ProductDetail> productDetailList = new ArrayList<>();
        String token = LocalUser.getToken();
        for (OrderDetail orderDetail : orderDetails) {
            String productId = orderDetail.getProductId();
            DataResult productResult = productFeign.getProductById(token,productId);
            LinkedHashMap productHashMap = (LinkedHashMap) productResult.getData();
            Product product = JSON.parseObject(JSON.toJSONString(productHashMap), Product.class);
            log.print("print product is" + product.getProductName());
            ProductDetail productDetail = new ProductDetail();
            productDetail.setProductName(product.getProductName());
            productDetail.setPrice(product.getPrice());
            productDetail.setProductId(product.getProductId());
            productDetail.setImage(product.getImage());
            productDetail.setAmount(orderDetail.getAmount());

            productDetailList.add(productDetail);
        }

        //从user微服务获取用户信息，远程调用
        UserVo userInfo = getUserInfo(order.getUserId());

        //将购买的产品信息和用户信息组装最后的响应体
        OrderDetailRsp orderDetailRsp = new OrderDetailRsp();
        orderDetailRsp.setProductDetailList(productDetailList);
        orderDetailRsp.setUserName(userInfo.getUserName());
        orderDetailRsp.setPhone(userInfo.getPhone());
        orderDetailRsp.setOrderId(order.getOrderId());
        orderDetailRsp.setStatus(order.getStatus());
        orderDetailRsp.setUserId(userInfo.getUserId());
        return orderDetailRsp;
    }

    private IPage<OrderDetailRsp> getMultiOrderDetailInfo(int current, int size, String userId) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq(userId != null ,"user_id", userId);
        Page<Order> page = new Page<>(current, size);
        IPage<Order> orderPage = orderService.page(page, wrapper);
        IPage<OrderDetailRsp> orderDetailRspIPage = new Page<>();
        orderDetailRspIPage.setPages(orderPage.getPages());
        orderDetailRspIPage.setCurrent(orderPage.getCurrent());
        orderDetailRspIPage.setTotal(orderPage.getTotal());
        orderDetailRspIPage.setSize(orderPage.getSize());
        List<Order> orderList = orderPage.getRecords();
        List<OrderDetailRsp> orderDetailRspList = new ArrayList<>();
        for (Order order:orderList) {
            OrderDetailRsp orderDetailRsp = getOneOrderDetailInfo(order.getOrderId());
            orderDetailRspList.add(orderDetailRsp);
        }
        orderDetailRspIPage.setRecords(orderDetailRspList);
        return orderDetailRspIPage;
    }
}
